﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using Tools.beans;
using Tools.FileUtills;
using Image = System.Windows.Controls.Image;

namespace Tools
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : INotifyPropertyChanged
    {
        /**
         * 搜索关键字 
         */
        private String queryKey;


        /// <summary>
        ///  分割名称的符号
        /// </summary>
        public static String spliteName = "@";


 
        
   
        private List<ToolsBean> tools = new List<ToolsBean>();

    
        public MainWindow()
        {
            InitializeComponent();
            initDeskTopData();
        }


        /// <summary>
        ///  初始化加载添加了的文件列表 
        /// </summary>
        public void initDeskTopData()
        {
            tools.Clear();
            var toolsBox = FindName("toolPanel") as ListBox;
            toolsBox.ItemsSource = null;
            var fileList = FileUtils.readFile();
            foreach (var item in fileList)
            {
                if ("".Equals(item))
                {
                    break;
                }

                FileInfo info = new FileInfo(item);

                //var fileStep = item.Split('\\');
                //var fileName = fileStep[fileStep.Length - 1].Split('.')[0];
                var fileName_path =  item.Split('@');
                var fileIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileName_path[0]);
                BitmapSource icon_source = Imaging.CreateBitmapSourceFromHIcon(
                    fileIcon.Handle,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions()
                );
                tools.Add(new ToolsBean(fileName_path[1], fileName_path[0], icon_source));
            }

            toolsBox.ItemsSource = tools;
        }


        public void test()
        {
            
        }
        /**
         * 开始搜索
         */
        public void StartSearch(Object o, EventArgs args)
        {
            var tb_search = this.FindName("tb_search") as TextBox;

            var fileName = tb_search.Text;

            
            var findFileResult = FileUtils.findFileByFileName(fileName);
            if (findFileResult.Count == 0)
            {
                initDeskTopData();
                return;
            }
            var toolsBox = FindName("toolPanel") as ListBox;
            toolsBox.ItemsSource = null;
            tools.Clear();
            foreach (var item in findFileResult)
            {
                if ("".Equals(item))
                {
                    break;
                }
                
                var fileName_path = ((string)item).Split('@');
                var fileIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileName_path[0]);
                BitmapSource icon_source = Imaging.CreateBitmapSourceFromHIcon(
                    fileIcon.Handle,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions()
                );
                tools.Add(new ToolsBean(fileName_path[1], fileName_path[0], icon_source));
            }
            toolsBox.ItemsSource = tools;
        }


    


        /// <summary>
        /// 添加 桌面图标 信息 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void add_deskTop_info(object sender, MouseButtonEventArgs e)
        {
            // 1. 打开文件选择器
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false; //该值确定是否可以选择多个文件
            dialog.Title = "请选择EXE文件";
            dialog.Filter = "所有文件(*.*)|*.exe";
            if (dialog.ShowDialog().Value)
            {
                try
                {
                    var toolsBox = FindName("toolPanel") as ListBox;
                    var selectedFilPath = dialog.FileName;
                    FileInfo fileInfo = new FileInfo(selectedFilPath);
                    var fileIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName);
                    var fileStep = selectedFilPath.Split('\\');
                    var fileName = fileStep[fileStep.Length - 1].Split('.')[0];
                    selectedFilPath = selectedFilPath + "@" + fileName;

                   if (!FileUtils.readFile().Contains(selectedFilPath))
                    {
                        FileUtils.addItemInfo(selectedFilPath);
                    }
                   else
                    {
                        MessageBox.Show("当前文件已存在");
                    }
                
                    initDeskTopData();
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                    throw;
                }
            }
            else
            {
                MessageBox.Show("文件打开失败");
            }
        }
        


        /// <summary>
        ///  双击子列表选项 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoubleClickListItem(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var toolPanel = FindName("toolPanel") as ListBox;
                var selectToolBean = toolPanel.SelectedItem as ToolsBean;
                new  Thread(() =>
                {
                    startExe(selectToolBean.FilePath);
                }).Start();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                MessageBox.Show("启动失败");
            }
          
        }


        public void startExe(String exe_path)
        {
            Process.Start(exe_path);
        }

        private void StartUpdateFileName(object sender, MouseButtonEventArgs e)
        {
            try
            {
               
                var toolPanel = FindName("toolPanel") as ListBox;
                var selectToolBean = toolPanel.SelectedItem as ToolsBean;
                MessageBox.Show(selectToolBean.FileName);
                SettingExeInfo settingExeInfo = new SettingExeInfo();
                SettingExeInfo.CurrentFileName = selectToolBean.FileName;
                SettingExeInfo.CurrnetFilePath = selectToolBean.FilePath;
                settingExeInfo.Show();
                Close();
            }
            catch (Exception exception)
            {

                MessageBox.Show(exception.Message);

            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }
}